#include <opencv2/opencv.hpp>
#include <thread>
#include <mutex>
#include <random>
using namespace cv;
using namespace std;

mutex mtx;
bool isTransmitting = false;
bool collisionDetected = false;

void sendFrame(int frame) {
    unique_lock<mutex> lock(mtx);
    if (isTransmitting) {
        collisionDetected = true;
        cout << "Collision detected!" << endl;
        return;
    }
    isTransmitting = true;
    lock.unlock();

    Mat img(480, 640, CV_8UC3, Scalar(0, 255, 0));
    imshow("Sender", img);
    waitKey(1000);

    lock.lock();
    isTransmitting = false;
    collisionDetected = false;
}

void receiveFrame() {
    VideoCapture cap(0);
    while (true) {
        Mat frame;
        cap >> frame;
        if (frame.empty()) continue;
        Scalar meanColor = mean(frame);
        if (meanColor[1] > 200) {
            cout << "Frame received" << endl;
            unique_lock<mutex> lock(mtx);
            isTransmitting = false;
        }
        imshow("Receiver", frame);
        if (waitKey(30) == 27) break;
    }
}

int main() {
    thread receiver(receiveFrame);
    this_thread::sleep_for(chrono::seconds(2));
    for (int i = 0; i < 5; i++) {
        this_thread::sleep_for(chrono::milliseconds(rand() % 2000));
        thread sender(sendFrame, i);
        sender.join();
    }
    receiver.join();
    destroyAllWindows();
    return 0;
}